package server;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;

public class Lesson extends Thread{
    private Socket socket;

    public static HashSet<PrintWriter> arr =new HashSet<>();
    public Lesson(Socket socket) {
        this.socket = socket;
    }

    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }



    @Override
    public synchronized void start() {
        super.start();
    }

    @Override
    public void run() {
        super.run();

        try (

                InputStream it=socket.getInputStream();
                InputStreamReader itr=new InputStreamReader(it, StandardCharsets.UTF_8);
                BufferedReader bfr=new BufferedReader(itr);
                OutputStream ot=socket.getOutputStream();
                OutputStreamWriter osw=new OutputStreamWriter(ot,StandardCharsets.UTF_8);
                BufferedWriter bfw=new BufferedWriter(osw);
                PrintWriter pw=new PrintWriter(bfw,true);
                ){
            System.out.println("开始");
            arr.add(pw);
            String s;
            while ((s= bfr.readLine())!=null){
                System.out.println(socket.getInetAddress().getHostAddress()+s);


                for(PrintWriter  bwt:arr
                     ) {
                    if (!bwt.equals(pw)){
                        bwt.println(s);
                    }
                }


                Thread.sleep(500);
            }


        }catch (IOException | InterruptedException e){
            System.out.println(e.getMessage());
            System.out.println("2");
        }

    }
    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("结束");
    }
}
